package com.frxuexi.shop2307.user

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.entity.CodeBean
import com.frxuexi.lib_base.mvvm.BaseActivity
import com.frxuexi.shop2307.R
import com.frxuexi.shop2307.databinding.ActivityFindPassBinding
import com.google.gson.Gson
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Timer
import kotlin.concurrent.timerTask

@Route(path = "/app/FindPassActivity")
@AndroidEntryPoint
class FindPassActivity : BaseActivity<ActivityFindPassBinding,UserViewModel>() {

    var timer: Timer?=null
    var num=10
    override fun initData() {
        vm.codeData.observe(this){
            val codeBean = Gson().fromJson<CodeBean>(it.content, CodeBean::class.java)
            ToastUtils.showLong(codeBean.code)
        }

        vm.findData.observe(this){
            ToastUtils.showLong("修改成功")
        }
    }

    override fun initView() {
        binding.findBtn.setOnClickListener {
            val phone = binding.findPhone.text.toString()
            val code = binding.findCode.text.toString()
            val pass = binding.findPass.text.toString()
            val pass2 = binding.findPass2.text.toString()
            
            vm.findPass(mapOf("account" to phone,"captcha" to code,"password" to  pass))
        }

        binding.findSendCode.setOnClickListener {
            val phone = binding.findPhone.text.toString()
            if(phone.isNullOrEmpty()){
                ToastUtils.showLong("手机号不能为空")
                return@setOnClickListener
            }
            if(!RegexUtils.isMobileSimple(phone)){
                ToastUtils.showLong("不是合法手机号")
                return@setOnClickListener
            }
            binding.findSendCode.isEnabled=false
            lifecycleScope.launch(Dispatchers.IO) {
                timer= Timer()
                timer!!.schedule(timerTask {
                    lifecycleScope.launch (Dispatchers.Main){
                        binding.findSendCode.setText("还剩 ${num--}s")
                        if(num==0){
                            timer!!.cancel()
                            binding.findSendCode.isEnabled=true
                            binding.findSendCode.setText("重新发送")
                            num=10
                        }
                    }
                },0,1000)
            }
            vm.sendCode(phone)
        }
    }

}